package org.adream.account.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.adream.account.dao.RoleDao;
import org.adream.account.dao.RoleResLinkDao;
import org.adream.account.dao.UserRoleLinkDao;
import org.adream.account.entity.RoleEntity;
import org.adream.account.entity.RoleResLinkEntity;
import org.adream.account.entity.UserRoleLinkEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.model.SynDream2020DataModel;
import org.adream.account.rest.api.model.RoleForm;
import org.adream.account.service.async.SynDream2020Service;
import org.adream.account.util.Constant;
import org.adream.account.util.IdGenerator;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class RoleService {
	private final static Logger logger = LoggerFactory.getLogger(RoleService.class);
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private RoleResLinkDao roleResLinkDao;
	
	@Autowired
	private UserRoleLinkDao userRoleLinkDao;
	
	@Autowired
	private SynDream2020Service synDream2020Service;
	
	@Autowired
	private HttpSession session;
	
	/**
	 * 新增角色及对应的权限
	 * @param form
	 * @param request
	 * @return
	 * @throws ADreamServiceException
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<String> saveRoleRes(RoleForm form, HttpServletRequest request) throws ADreamServiceException {
		RoleEntity role = new RoleEntity();
		Utils.copyPropertiesIgnoreNull(form, role);
		String rleId = IdGenerator.getGuid();
		role.setRleId(rleId);
		String operator = (String) session.getAttribute("uid");
		role.setCreator(operator);
		role.setModifier(operator);
		role.setDr(Constant.ONE);
		int result = roleDao.addRole(role);
		if(result == Constant.ZERO) {
			logger.warn("新增role失败:(");
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误r001,请联系管理员", null);
		}
		if(!Utils.isEmptyCollection(form.getResIds())) {
			List<String> resIds = form.getResIds();
			int size = resIds.size();
			for (int i = 0; i < size; i++) {
				RoleResLinkEntity roleRes = new RoleResLinkEntity();
				roleRes.setRleId(rleId);
				roleRes.setResId(resIds.get(i));
				roleRes.setDr(Constant.ONE);
				int roleResResult = roleResLinkDao.replaceRoleRes(roleRes);
				if(roleResResult == Constant.ZERO) {
					logger.warn("数据库错误,新增role-res中间表失败:(");
					throw new ADreamServiceException("系统错误r002,请联系管理员");
				}
			}
		}
		return new ResultModel<String>(ResultModel.SUCCESS, "成功新增role", null);
	}
	
	/**
	 * 删除角色  逻辑删除
	 * @param role
	 */
	public ResultModel<String> deleteRole(String rleId) {
		RoleEntity role = roleDao.queryRoleByRleIdAndDr(rleId, Constant.ONE);
		if(role == null) {
			logger.warn("删除角色失败,数据不存在,rleId:{}", rleId);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		}
		String modifier = (String) session.getAttribute("uid");
		role.setModifier(modifier);
		role.setDr(Constant.ZERO);
		int result = roleDao.deleteRole(role);
		if(result == 0) {
			logger.warn("删除角色失败,数据库错误,rleId:{}", rleId);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	/**
	 * 更新
	 * @param roleEntity
	 */
	public ResultModel<String> updateRole(RoleEntity roleEntity) {
		RoleEntity role = roleDao.queryRoleByRleIdAndDr(roleEntity.getRleId(), Constant.ONE);
		if(role == null) {
			logger.warn("更新角色失败,数据不存在,rleId:{}", roleEntity.getRleId());
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败,数据不存在", null);
		}
		String modifier = (String) session.getAttribute("uid");
		Utils.copyPropertiesIgnoreNull(roleEntity, role);
		role.setModifier(modifier);
		int result = roleDao.updateRole(role);
		if(result == 0) {
			logger.warn("更新角色数据失败,数据库错误,rleId:{}", roleEntity.getRleId());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}
	
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<?> updateRoleRes(RoleForm form, HttpServletRequest request) throws ADreamServiceException {
		RoleEntity role = roleDao.queryRoleByRleIdAndDr(form.getRleId(), Constant.ONE);
		if(role == null) {
			logger.warn("更新失败,数据不存在:(");
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败,请刷新重试", null);
		}
		role.setRleName(form.getRleName());
		role.setVerify(form.getVerify());
		role.setRleDesc(form.getRleDesc());
		String modifier = (String) session.getAttribute("uid");
		role.setModifier(modifier);
		int result = roleDao.updateRole(role);
		if(result == Constant.ZERO) {
			logger.warn("更新role失败:(");
			return new ResultModel<String>(ResultModel.ERR_DATABASE, "系统错误r003,请联系管理员", null);
		}
		//存在更新角色——权限关联操作
		if(form.getResIds() != null) {
			//先删除 role resource关联，再新增
			roleResLinkDao.deleteRoleResByRleId(form.getRleId());
			boolean isAdreamBoxAdmin = false;
			//resIds不为[]
			if(form.getResIds().size() > Constant.ZERO) {
				List<String> resIds = form.getResIds();
				int size = resIds.size();
				for (int i = 0; i < size; i++) {
					RoleResLinkEntity roleRes = new RoleResLinkEntity();
					roleRes.setRleId(form.getRleId());
					roleRes.setResId(resIds.get(i));
					roleRes.setDr(Constant.ONE);
					int roleResResult = roleResLinkDao.replaceRoleRes(roleRes);
					if(roleResResult == Constant.ZERO) {
						logger.warn("数据库错误,新增role-res中间表失败:(");
						throw new ADreamServiceException("系统错误r004,请联系管理员");
					}
					if(!isAdreamBoxAdmin && Constant.ADREAM_BOX_ADMIN.equals(resIds)) {
						isAdreamBoxAdmin = true;
					}
				}
			}
			/**
			 * 若角色有'梦想盒子后台管理'权限,查询有该角色的用户,同步数据
			 */
			if(isAdreamBoxAdmin) {
				UserRoleLinkEntity userRole = userRoleLinkDao.queryUidsByRleIdAndDr(form.getRleId(), Constant.ONE);					
				//同步数据
				if(userRole != null && !StringUtils.isEmpty(userRole.getUid())) {
					String[] uids = userRole.getUid().split(",");
					for (String uid: uids) {
						SynDream2020DataModel data = new SynDream2020DataModel();
						data.setCasid(uid);
						data.setIsAdreamboxAdmin(isAdreamBoxAdmin);
						synDream2020Service.synDream2020Data(data);
					}
				}
			}
		}
		return new ResultModel<String>(ResultModel.SUCCESS, "角色更新成功", null);
	}
	
	public List<RoleEntity> queryRolesByDr(int dr) {
		return roleDao.queryRolesByDr(dr);
	}
	
	public List<RoleEntity> queryRolesByVerifyAndDr(Integer verify,Integer dr) {
		return roleDao.queryRolesByVerifyAndDr(verify, dr);
	}
	
	/**
	 * 通过rleId查询Role
	 * @param rleId role id
	 * @return
	 */
	public RoleEntity queryRoleByRleId(String rleId) {
		return roleDao.queryRoleByRleId(rleId);
	}
	
	/**
	 * 检查角色名称是否存在
	 * @param rleName role name
	 * @return
	 */
	public boolean isValidRleName(String rleName) {
		boolean isValidRleName = false;
		RoleEntity role = roleDao.queryRoleByRleName(rleName);
		if(!StringUtils.isEmpty(rleName) && role == null) {
			isValidRleName = true;
		}
		return isValidRleName;
	}
	
	/**
	 * 根据角色id，删除标志查询
	 * @param rleId
	 * @param dr
	 * @return
	 */
	public RoleEntity queryRoleByRleIdAndDr(String rleId, int dr) {
		return roleDao.queryRoleByRleIdAndDr(rleId, dr);
	}
	
	/**
	 * 分页查询角色
	 * @param dr  删除标志
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public PageInfo<RoleEntity> selectPageRoles(Integer dr, Integer pageNo,Integer pageSize) {
		if(StringUtils.isEmpty(dr)) {
			logger.warn("查询出错,删除标志为空:(");
			return null;
		}
		pageNo = (pageNo == null) ? Constant.ONE : pageNo;
		pageSize = (pageSize == null) ? Constant.TEN : pageSize;
		PageHelper.startPage(pageNo,pageSize);
		List<RoleEntity> roles = roleDao.selectPageRoles(dr);
		PageInfo<RoleEntity> page = new PageInfo<>(roles,Constant.TEN);
		return page;
	}
	/**
	 * 	查询系统角色信息 不分页  
	 * 	对外接口使用（宅龙）最好不要修改
	 * @return {rleId:[角色ID],rleName:[角色名],rleDesc:[角色描述]}
	 * @throws ADreamServiceException
	 */
	public List<Map<String, Object>> getSysRoleInfo() throws ADreamServiceException{
		return roleDao.getSysRoleInfo();
	}
}